import Router from 'koa-router';
import { rename } from 'fs/promises';
import { join } from 'path';
import { ensureDir } from 'fs-extra';
import { UPLOAD_DIR } from '../config/constants.js';

const router = new Router({
  // prefix: '/apk'
});

router.post('/updates/upload', async (ctx) => {
  try {
    await ensureDir(UPLOAD_DIR);
    
    const file = ctx.request.files?.file;
    const app = ctx.request.body.app;
    console.log("###", ctx.request.body, app);
  
    if (!file) {
      ctx.status = 400;
      ctx.body = { success: false, message: 'No file uploaded' };
      return;
    }

    // Generate a unique filename to prevent overwrites
    const timestamp = Date.now();
    // const filename = `${timestamp}-${file.originalFilename}`;
    const filename = `mob.wgt`;
    const targetDir = app ? join(UPLOAD_DIR, app) : UPLOAD_DIR;
    await ensureDir(targetDir);
    const newPath = join(targetDir, filename);
    
    await rename(file.filepath, newPath);

    ctx.body = {
      success: true,
      message: 'File uploaded successfully',
      filename: filename,
      url: join(targetDir, filename)
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: 'Failed to upload file',
      error: error.message
    };
  }
});

export const uploadRouter = router;